package com.parmal.proxy.server;

import com.parmal.proxy.configuration.HttpProxyConfiguration;
import com.parmal.proxy.handler.http.HttpRequestAuthHandler;
import com.parmal.proxy.handler.http.HttpRequestDeliveryHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class HttpProxyServerStarter extends ProxyStarter {

    private NioEventLoopGroup bossGroup;

    private NioEventLoopGroup workerGroup;

    private ServerBootstrap serverBootstrap;

    private HttpProxyConfiguration configuration;

    private Bootstrap forwardBootStrap;

    private static Logger logger = LoggerFactory.getLogger(HttpProxyServerStarter.class);

    @Autowired
    public HttpProxyServerStarter(HttpProxyConfiguration configuration, Bootstrap forwardBootStrap) {
        this.configuration = configuration;
        this.forwardBootStrap = forwardBootStrap;
        this.init();
    }

    @Override
    protected void init() {
        this.bossGroup = new NioEventLoopGroup(this.configuration.bossEventLoopGroupCount);
        this.workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2);
        this.serverBootstrap = new ServerBootstrap();
        this.serverBootstrap.channel(NioServerSocketChannel.class);
        this.serverBootstrap.group(bossGroup, workerGroup).option(ChannelOption.SO_BACKLOG, 100).option(ChannelOption
                .SO_KEEPALIVE, true);

        this.serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast("http-decoder", new HttpRequestDecoder());
                socketChannel.pipeline().addLast(new HttpObjectAggregator(65535));
                socketChannel.pipeline().addLast(configuration.httpAuthHandlerName, new HttpRequestAuthHandler
                        (configuration));
                socketChannel.pipeline().addLast(new HttpRequestDeliveryHandler(configuration, forwardBootStrap));
            }
        });
    }

    @Override
    public ServerBootstrap start() {
        try {
            ChannelFuture future = this.serverBootstrap.bind(this.configuration.listenPort).sync();
            logger.info("服务启动在[{}]端口", this.configuration.listenPort);
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
        return this.serverBootstrap;
    }
}
